package com.zhugang.week01;

/**
 * @program algorithms
 * @description: reverseStr
 * @author: chanzhugang
 * @create: 2022/03/14 07:51
 */
public class ReverseStr {

    public static void main(String[] args) {
        ReverseStr reverseStr = new ReverseStr();
        char[] chars = new char[]{'h', 'e', 'l', 'l', 'o', 'j', 'a', 'v', 'a'};
        char[] result = reverseStr.reverseStr2(chars);
        System.out.println(result);
    }

    /**
     * 反转字符串，使用O(1)空间复杂度解决
     * 遍历一半数据，交换前后位置
     *
     * @param s
     * @return
     */
    public char[] reverseStr(char[] s) {
        int n = s.length;
        for (int i = 0; i < n / 2; i++) {
            char temp = s[i];
            s[i] = s[n - i - 1];
            s[n - i - 1] = temp;
        }
        return s;
    }

    /**
     * 双指针控制下标
     *
     * @param s
     * @return
     */
    public char[] reverseStr2(char[] s) {
        int n = s.length;
        int i = 0;
        int j = n - 1;
        while (i <= j) {
            char temp = s[i];
            s[i] = s[j];
            s[j] = temp;
            i++;
            j--;
        }
        return s;
    }
}